import requests
import csv
import json

headers = {
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'
}

c = open("/data/盒马鲜生.csv", "w")
writer = csv.writer(c)
writer.writerow(['国家','省','城市','区县','地址','店名','经度','维度'])

citys = ['北京市', '上海市','重庆市','宁波市','杭州市','苏州市','南京市','无锡市','南通市','合肥市','青岛市','深圳市','广州市','佛山市','沈阳市','大连市','武汉市','郑州市',
         '西安市','长沙市','成都市','贵阳市','海口市','三亚市','昆明市']

# 需要去官方网站注册申请
key = ''
for ci in citys:
    for page in range (1,7):
        url = f'https://restapi.amap.com/v3/place/text?key={key}&keywords=盒马鲜生&children=1&city={ci}&offset=20&page={page}&extensions=all'
        print(url)
        rep = requests.get(url, headers=headers)

        content = rep.content.decode('utf-8')
        pois = json.loads(content)['pois']

        for poi in pois:
            pname = poi.get('pname', '')
            cityname = poi.get('cityname', '')
            adname = poi.get('adname', '')
            name = poi.get('name', '')
            address = poi.get('address', '')
            location = poi.get('location', '')
            ln = ''
            sn = ''
            if location:
                sp = location.split(',')
                ln = sp[0]
                sn = sp[1]
            print(pname,cityname ,adname ,address , name, ln, sn)
            writer.writerow(['中国',pname,cityname ,adname ,address , name, ln, sn])
